home *** CD-ROM | disk | FTP | other *** search
/ Enter 2006 September / Enter 09 2006.iso / Internet / SpamExperts Home 1.1 / SpamExperts Home.exe / lib / spamexperts.modules / email / Header.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2006-07-14  |  13.2 KB  |  415 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.4)
  3.  
  4. '''Header encoding and decoding functionality.'''
  5. import re
  6. import binascii
  7. import email.quopriMIME as email
  8. import email.base64MIME as email
  9. from email.Errors import HeaderParseError
  10. from email.Charset import Charset
  11. NL = '\n'
  12. SPACE = ' '
  13. USPACE = u' '
  14. SPACE8 = ' ' * 8
  15. UEMPTYSTRING = u''
  16. MAXLINELEN = 76
  17. USASCII = Charset('us-ascii')
  18. UTF8 = Charset('utf-8')
  19. ecre = re.compile('\n  =\\?                   # literal =?\n  (?P<charset>[^?]*?)   # non-greedy up to the next ? is the charset\n  \\?                    # literal ?\n  (?P<encoding>[qb])    # either a "q" or a "b", case insensitive\n  \\?                    # literal ?\n  (?P<encoded>.*?)      # non-greedy up to the next ?= is the encoded string\n  \\?=                   # literal ?=\n  ', re.VERBOSE | re.IGNORECASE)
  20. fcre = re.compile('[\\041-\\176]+:$')
  21. _max_append = email.quopriMIME._max_append
  22.  
  23. def decode_header(header):
  24.     '''Decode a message header value without converting charset.
  25.  
  26.     Returns a list of (decoded_string, charset) pairs containing each of the
  27.     decoded parts of the header.  Charset is None for non-encoded parts of the
  28.     header, otherwise a lower-case string containing the name of the character
  29.     set specified in the encoded string.
  30.  
  31.     An email.Errors.HeaderParseError may be raised when certain decoding error
  32.     occurs (e.g. a base64 decoding exception).
  33.     '''
  34.     header = str(header)
  35.     if not ecre.search(header):
  36.         return [
  37.             (header, None)]
  38.     
  39.     decoded = []
  40.     dec = ''
  41.     for line in header.splitlines():
  42.         if not ecre.search(line):
  43.             decoded.append((line, None))
  44.             continue
  45.         
  46.         parts = ecre.split(line)
  47.         while parts:
  48.             unenc = parts.pop(0).strip()
  49.             if unenc:
  50.                 if decoded and decoded[-1][1] is None:
  51.                     decoded[-1] = (decoded[-1][0] + SPACE + unenc, None)
  52.                 else:
  53.                     decoded.append((unenc, None))
  54.             
  55.             if parts:
  56.                 (charset, encoding) = [ s.lower() for s in parts[0:2] ]
  57.                 encoded = parts[2]
  58.                 dec = None
  59.                 if encoding == 'q':
  60.                     dec = email.quopriMIME.header_decode(encoded)
  61.                 elif encoding == 'b':
  62.                     
  63.                     try:
  64.                         dec = email.base64MIME.decode(encoded)
  65.                     except binascii.Error:
  66.                         []
  67.                         []
  68.                         raise HeaderParseError
  69.                     except:
  70.                         []<EXCEPTION MATCH>binascii.Error
  71.                     
  72.  
  73.                 []
  74.                 if dec is None:
  75.                     dec = encoded
  76.                 
  77.                 if decoded and decoded[-1][1] == charset:
  78.                     decoded[-1] = (decoded[-1][0] + dec, decoded[-1][1])
  79.                 else:
  80.                     decoded.append((dec, charset))
  81.             
  82.             del parts[0:3]
  83.     
  84.     return decoded
  85.  
  86.  
  87. def make_header(decoded_seq, maxlinelen = None, header_name = None, continuation_ws = ' '):
  88.     '''Create a Header from a sequence of pairs as returned by decode_header()
  89.  
  90.     decode_header() takes a header value string and returns a sequence of
  91.     pairs of the format (decoded_string, charset) where charset is the string
  92.     name of the character set.
  93.  
  94.     This function takes one of those sequence of pairs and returns a Header
  95.     instance.  Optional maxlinelen, header_name, and continuation_ws are as in
  96.     the Header constructor.
  97.     '''
  98.     h = Header(maxlinelen = maxlinelen, header_name = header_name, continuation_ws = continuation_ws)
  99.     for s, charset in decoded_seq:
  100.         if charset is not None and not isinstance(charset, Charset):
  101.             charset = Charset(charset)
  102.         
  103.         h.append(s, charset)
  104.     
  105.     return h
  106.  
  107.  
  108. class Header:
  109.     
  110.     def __init__(self, s = None, charset = None, maxlinelen = None, header_name = None, continuation_ws = ' ', errors = 'strict'):
  111.         """Create a MIME-compliant header that can contain many character sets.
  112.  
  113.         Optional s is the initial header value.  If None, the initial header
  114.         value is not set.  You can later append to the header with .append()
  115.         method calls.  s may be a byte string or a Unicode string, but see the
  116.         .append() documentation for semantics.
  117.  
  118.         Optional charset serves two purposes: it has the same meaning as the
  119.         charset argument to the .append() method.  It also sets the default
  120.         character set for all subsequent .append() calls that omit the charset
  121.         argument.  If charset is not provided in the constructor, the us-ascii
  122.         charset is used both as s's initial charset and as the default for
  123.         subsequent .append() calls.
  124.  
  125.         The maximum line length can be specified explicit via maxlinelen.  For
  126.         splitting the first line to a shorter value (to account for the field
  127.         header which isn't included in s, e.g. `Subject') pass in the name of
  128.         the field in header_name.  The default maxlinelen is 76.
  129.  
  130.         continuation_ws must be RFC 2822 compliant folding whitespace (usually
  131.         either a space or a hard tab) which will be prepended to continuation
  132.         lines.
  133.  
  134.         errors is passed through to the .append() call.
  135.         """
  136.         if charset is None:
  137.             charset = USASCII
  138.         
  139.         if not isinstance(charset, Charset):
  140.             charset = Charset(charset)
  141.         
  142.         self._charset = charset
  143.         self._continuation_ws = continuation_ws
  144.         cws_expanded_len = len(continuation_ws.replace('\t', SPACE8))
  145.         self._chunks = []
  146.         if s is not None:
  147.             self.append(s, charset, errors)
  148.         
  149.         if maxlinelen is None:
  150.             maxlinelen = MAXLINELEN
  151.         
  152.         if header_name is None:
  153.             self._firstlinelen = maxlinelen
  154.         else:
  155.             self._firstlinelen = maxlinelen - len(header_name) - 2
  156.         self._maxlinelen = maxlinelen - cws_expanded_len
  157.  
  158.     
  159.     def __str__(self):
  160.         '''A synonym for self.encode().'''
  161.         return self.encode()
  162.  
  163.     
  164.     def __unicode__(self):
  165.         '''Helper for the built-in unicode function.'''
  166.         uchunks = []
  167.         lastcs = None
  168.         for s, charset in self._chunks:
  169.             nextcs = charset
  170.             if uchunks:
  171.                 if lastcs not in (None, 'us-ascii'):
  172.                     if nextcs in (None, 'us-ascii'):
  173.                         uchunks.append(USPACE)
  174.                         nextcs = None
  175.                     
  176.                 elif nextcs not in (None, 'us-ascii'):
  177.                     uchunks.append(USPACE)
  178.                 
  179.             
  180.             lastcs = nextcs
  181.             uchunks.append(unicode(s, str(charset)))
  182.         
  183.         return UEMPTYSTRING.join(uchunks)
  184.  
  185.     
  186.     def __eq__(self, other):
  187.         return other == self.encode()
  188.  
  189.     
  190.     def __ne__(self, other):
  191.         return not (self == other)
  192.  
  193.     
  194.     def append(self, s, charset = None, errors = 'strict'):
  195.         """Append a string to the MIME header.
  196.  
  197.         Optional charset, if given, should be a Charset instance or the name
  198.         of a character set (which will be converted to a Charset instance).  A
  199.         value of None (the default) means that the charset given in the
  200.         constructor is used.
  201.  
  202.         s may be a byte string or a Unicode string.  If it is a byte string
  203.         (i.e. isinstance(s, str) is true), then charset is the encoding of
  204.         that byte string, and a UnicodeError will be raised if the string
  205.         cannot be decoded with that charset.  If s is a Unicode string, then
  206.         charset is a hint specifying the character set of the characters in
  207.         the string.  In this case, when producing an RFC 2822 compliant header
  208.         using RFC 2047 rules, the Unicode string will be encoded using the
  209.         following charsets in order: us-ascii, the charset hint, utf-8.  The
  210.         first character set not to provoke a UnicodeError is used.
  211.  
  212.         Optional `errors' is passed as the third argument to any unicode() or
  213.         ustr.encode() call.
  214.         """
  215.         if charset is None:
  216.             charset = self._charset
  217.         elif not isinstance(charset, Charset):
  218.             charset = Charset(charset)
  219.         
  220.         if charset != '8bit':
  221.             if isinstance(s, str):
  222.                 if not charset.input_codec:
  223.                     pass
  224.                 incodec = 'us-ascii'
  225.                 ustr = unicode(s, incodec, errors)
  226.                 if not charset.output_codec:
  227.                     pass
  228.                 outcodec = 'us-ascii'
  229.                 ustr.encode(outcodec, errors)
  230.             elif isinstance(s, unicode):
  231.                 for charset in (USASCII, charset, UTF8):
  232.                     
  233.                     try:
  234.                         if not charset.output_codec:
  235.                             pass
  236.                         outcodec = 'us-ascii'
  237.                         s = s.encode(outcodec, errors)
  238.                     continue
  239.                     except UnicodeError:
  240.                         continue
  241.                     
  242.  
  243.                 elif not False:
  244.                     raise AssertionError, 'utf-8 conversion failed'
  245.                 None<EXCEPTION MATCH>UnicodeError
  246.             
  247.         
  248.         self._chunks.append((s, charset))
  249.  
  250.     
  251.     def _split(self, s, charset, maxlinelen, splitchars):
  252.         splittable = charset.to_splittable(s)
  253.         encoded = charset.from_splittable(splittable, True)
  254.         elen = charset.encoded_header_len(encoded)
  255.         if elen <= maxlinelen:
  256.             return [
  257.                 (encoded, charset)]
  258.         
  259.         if charset == '8bit':
  260.             return [
  261.                 (s, charset)]
  262.         elif charset == 'us-ascii':
  263.             return self._split_ascii(s, charset, maxlinelen, splitchars)
  264.         elif elen == len(s):
  265.             splitpnt = maxlinelen
  266.             first = charset.from_splittable(splittable[:splitpnt], False)
  267.             last = charset.from_splittable(splittable[splitpnt:], False)
  268.         else:
  269.             (first, last) = _binsplit(splittable, charset, maxlinelen)
  270.         fsplittable = charset.to_splittable(first)
  271.         fencoded = charset.from_splittable(fsplittable, True)
  272.         chunk = [
  273.             (fencoded, charset)]
  274.         return chunk + self._split(last, charset, self._maxlinelen, splitchars)
  275.  
  276.     
  277.     def _split_ascii(self, s, charset, firstlen, splitchars):
  278.         chunks = _split_ascii(s, firstlen, self._maxlinelen, self._continuation_ws, splitchars)
  279.         return zip(chunks, [
  280.             charset] * len(chunks))
  281.  
  282.     
  283.     def _encode_chunks(self, newchunks, maxlinelen):
  284.         chunks = []
  285.         for header, charset in newchunks:
  286.             if not header:
  287.                 continue
  288.             
  289.             if charset is None or charset.header_encoding is None:
  290.                 s = header
  291.             else:
  292.                 s = charset.header_encode(header)
  293.             if chunks and chunks[-1].endswith(' '):
  294.                 extra = ''
  295.             else:
  296.                 extra = ' '
  297.             _max_append(chunks, s, maxlinelen, extra)
  298.         
  299.         joiner = NL + self._continuation_ws
  300.         return joiner.join(chunks)
  301.  
  302.     
  303.     def encode(self, splitchars = ';, '):
  304.         """Encode a message header into an RFC-compliant format.
  305.  
  306.         There are many issues involved in converting a given string for use in
  307.         an email header.  Only certain character sets are readable in most
  308.         email clients, and as header strings can only contain a subset of
  309.         7-bit ASCII, care must be taken to properly convert and encode (with
  310.         Base64 or quoted-printable) header strings.  In addition, there is a
  311.         75-character length limit on any given encoded header field, so
  312.         line-wrapping must be performed, even with double-byte character sets.
  313.  
  314.         This method will do its best to convert the string to the correct
  315.         character set used in email, and encode and line wrap it safely with
  316.         the appropriate scheme for that character set.
  317.  
  318.         If the given charset is not known or an error occurs during
  319.         conversion, this function will return the header untouched.
  320.  
  321.         Optional splitchars is a string containing characters to split long
  322.         ASCII lines on, in rough support of RFC 2822's `highest level
  323.         syntactic breaks'.  This doesn't affect RFC 2047 encoded lines.
  324.         """
  325.         newchunks = []
  326.         maxlinelen = self._firstlinelen
  327.         lastlen = 0
  328.         for s, charset in self._chunks:
  329.             targetlen = maxlinelen - lastlen - 1
  330.             if targetlen < charset.encoded_header_len(''):
  331.                 targetlen = maxlinelen
  332.             
  333.             newchunks += self._split(s, charset, targetlen, splitchars)
  334.             (lastchunk, lastcharset) = newchunks[-1]
  335.             lastlen = lastcharset.encoded_header_len(lastchunk)
  336.         
  337.         return self._encode_chunks(newchunks, maxlinelen)
  338.  
  339.  
  340.  
  341. def _split_ascii(s, firstlen, restlen, continuation_ws, splitchars):
  342.     lines = []
  343.     maxlen = firstlen
  344.     for line in s.splitlines():
  345.         line = line.lstrip()
  346.         if len(line) < maxlen:
  347.             lines.append(line)
  348.             maxlen = restlen
  349.             continue
  350.         
  351.         for ch in splitchars:
  352.             if ch in line:
  353.                 break
  354.                 continue
  355.         else:
  356.             maxlen = restlen
  357.         cre = re.compile('%s\\s*' % ch)
  358.         if ch in ';,':
  359.             eol = ch
  360.         else:
  361.             eol = ''
  362.         joiner = eol + ' '
  363.         joinlen = len(joiner)
  364.         wslen = len(continuation_ws.replace('\t', SPACE8))
  365.         this = []
  366.         linelen = 0
  367.         for part in cre.split(line):
  368.             curlen = linelen + max(0, len(this) - 1) * joinlen
  369.             partlen = len(part)
  370.             onfirstline = not lines
  371.             if ch == ' ' and onfirstline and len(this) == 1 and fcre.match(this[0]):
  372.                 this.append(part)
  373.                 linelen += partlen
  374.                 continue
  375.             if curlen + partlen > maxlen:
  376.                 if this:
  377.                     lines.append(joiner.join(this) + eol)
  378.                 
  379.                 if partlen > maxlen and ch != ' ':
  380.                     subl = _split_ascii(part, maxlen, restlen, continuation_ws, ' ')
  381.                     lines.extend(subl[:-1])
  382.                     this = [
  383.                         subl[-1]]
  384.                 else:
  385.                     this = [
  386.                         part]
  387.                 linelen = wslen + len(this[-1])
  388.                 maxlen = restlen
  389.                 continue
  390.             this.append(part)
  391.             linelen += partlen
  392.         
  393.         if this:
  394.             lines.append(joiner.join(this))
  395.             continue
  396.     
  397.     return lines
  398.  
  399.  
  400. def _binsplit(splittable, charset, maxlinelen):
  401.     i = 0
  402.     j = len(splittable)
  403.     while i < j:
  404.         m = i + j + 1 >> 1
  405.         chunk = charset.from_splittable(splittable[:m], True)
  406.         chunklen = charset.encoded_header_len(chunk)
  407.         if chunklen <= maxlinelen:
  408.             i = m
  409.             continue
  410.         j = m - 1
  411.     first = charset.from_splittable(splittable[:i], False)
  412.     last = charset.from_splittable(splittable[i:], False)
  413.     return (first, last)
  414.  
  415.